const https = require('https')
const express = require('express')
var bodyParser =require('body-parser')


const app = express()
const port = 3000
let SQLHelper = require('./SQLHelper')

// SQLHelper('select * from product').then(ret =>{
//     console.log('I am mysql',ret)
// })

//解析body中间件
app.use(bodyParser.json({limit:'100mb'}));


//微信登陆
app.get('/wx/login', (req, res) => {
    let code = req.query.code
    let appid = 'wx2378338cf7d6e42c'
    let secret = '229a44ae04c046373505f4f9eb553381'
    https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`, (ret) => {
        ret.on('data', (ret) => {
            ret = JSON.parse(ret.toString())
            let openid = ret.openid
            if(!openid){
                res.send({errorMsg: ret.errMsg || '获取openid错误'})
            }else{
                let queryMember = `select * from member where openId ='${openid}'`
                SQLHelper(queryMember).then(membersRet =>{
                    console.log(membersRet)
                    if(membersRet.length){
                        res.send(membersRet[0])
                    }else{
                        SQLHelper(`INSERT INTO member(openId) VALUES('${openid}')`).then(newMember =>{
                            //
                            SQLHelper(queryMember).then(newMember =>{
                                res.send(newMember)
                            })
                        })
                    }
                })
            }
        });

    }).on('error', (e) => {
        console.error(e);
        res.send({errorMsg:'获取openid错误'})
    });


})

//修改信息
app.put('/wx/member',(req,res)=>{
    //
    let userInfo=req.body
    SQLHelper(`
    update member 
    set nickName = '${userInfo.nickName}',avatarUrl='${userInfo.avatarUrl}'
    where _id =${userInfo._id}
     `).then(ret =>{
        //
        console.log(ret)
        res.send({})
    })
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})